package com.example.blog.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2025/7/29
 * Time: 14:49
 */
@Slf4j
public class JwtUtil {
    private static final String secret = "af6QgyY94GAE3vijSuxvft72nla6c8HjtWMRgTd/1nk="; // 签名信息
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)); // 字符串转成 byte 数组

    // 24 小时过期
    private static final long expiration = 24 * 60 * 60 * 1000;

    // 1. 生成 token
    public static String genToken(Map<String, Object> map) {

        return Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + expiration)) // 设置过期时间
                .setIssuedAt(new Date()) // 设置签发时间
                .signWith(key)
                .compact();
    }


    // 2. 校验 token
    public static Claims parseToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        // JWT 解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();
            return body;
        } catch (ExpiredJwtException e) {
            log.error("token 过期, token: {}", token);
        } catch (SignatureException e) {
            log.error("签名不匹配, token:{}", token);
        } catch (Exception e) {
            log.error("token 解析失败, token:{}", token);
        }
        return null;
    }
}
